package com.nmdl.test2;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;

public class BleHelper {
    public static final String TAG = "BleHelper";
    public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    public static BluetoothDevice socketDevice;
    public static BluetoothSocket clientSocket;
    public static OutputStream outputStream;

    public static void closeDeviceClient(BluetoothAdapter blueToothClient) {
        if (blueToothClient != null && blueToothClient.isDiscovering()) {
            blueToothClient.cancelDiscovery();
        }
    }

    /**
     * 与设备配对
     *
     * @param device
     */
    public static void bond(BluetoothDevice device) {
        try {
            Log.e(TAG, "开始配对");
            Method method = BluetoothDevice.class.getMethod("createBond");
            method.invoke(device);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 与设备解除配对
     *
     * @return
     */
    public static boolean removeBonds(BluetoothDevice device) {
        try {
            Log.e(TAG, "解除配对");
            Method removeBondMethod = BluetoothDevice.class.getMethod("removeBond");
            removeBondMethod.invoke(device);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private static byte[] getImageData(Context context) {
        try {
            InputStream open = context.getAssets().open("share_icon.png");
            Bitmap bitmap = BitmapFactory.decodeStream(open); //得到每个图片
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] data = baos.toByteArray();
            return data;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static byte[] getMediaData(Context context) {
        try {
            InputStream open = context.getAssets().open("1638.wav");
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            for (int readNum; (readNum = open.read(b)) != -1; ) {
                bos.write(b, 0, readNum);
            }
            byte[] bytes = bos.toByteArray();
            return bytes;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 连接设备
     */
    public static void connectDevice(BluetoothAdapter blueToothClient, BluetoothDevice device, Context context) {
        closeDeviceClient(blueToothClient);
        try {
            Method m = device.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
            if (clientSocket == null || socketDevice != device) {
                clientSocket = (BluetoothSocket) m.invoke(device, Integer.valueOf(1));
                clientSocket.connect();
                // 获取到输出流，向外写数据
                outputStream = clientSocket.getOutputStream();
                socketDevice = device;
            }
            // 判断是否拿到输出流
            if (outputStream != null) {
                // 需要发送的信息
                String text = "成功发送信息";
                // 以utf-8的格式发送出去

                outputStream.write(text.getBytes("UTF-8"));
//                outputStream.write(getImageData(context));
                outputStream.flush();
                // 吐司一下，告诉用户发送成功
                Toast.makeText(context, "发送信息成功，请查收", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "发送信息失败", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 如果发生异常则告诉用户发送失败
            Toast.makeText(context, "发送信息失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 连接设备
     */
    public static void connectDeviceService(BluetoothAdapter blueToothClient, BluetoothDevice device, Context context) {
        closeDeviceClient(blueToothClient);
        try {
            if (clientSocket == null || socketDevice != device) {
//                            clientSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
                clientSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
                // 向服务端发送连接
                clientSocket.connect();
                // 获取到输出流，向外写数据
                outputStream = clientSocket.getOutputStream();
                socketDevice = device;
            }
            // 判断是否拿到输出流
            if (outputStream != null) {
                // 需要发送的信息
                String text = "成功发送信息";
                // 以utf-8的格式发送出去
                outputStream.write(text.getBytes("UTF-8"));
                // 吐司一下，告诉用户发送成功
                Toast.makeText(context, "发送信息成功，请查收", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "发送信息失败", Toast.LENGTH_SHORT).show();
            }
        } catch (IOException e) {
            e.printStackTrace();
            // 如果发生异常则告诉用户发送失败
            Toast.makeText(context, "发送信息失败", Toast.LENGTH_SHORT).show();
        }
    }

    @SuppressWarnings("unchecked")
    public static boolean setPin(BluetoothDevice btDevice, String str) {
        try {
            Method removeBondMethod = btDevice.getClass().getDeclaredMethod("setPin", new Class[]{byte[].class});
            Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice, new Object[]{str.getBytes()});
            Log.d("returnValue", "setPin is success " + btDevice.getAddress() + returnValue.booleanValue());
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 连接蓝牙audio设备
     */
    public static void connectDeviceAudio(BluetoothAdapter blueToothClient, BluetoothDevice device, Context context) {
        if (device.getBluetoothClass().getMajorDeviceClass() != BluetoothClass.Device.Major.AUDIO_VIDEO) {
            return;
        }
        blueToothClient.getProfileProxy(context, new BluetoothProfile.ServiceListener() {
            @Override
            public void onServiceConnected(int profile, BluetoothProfile proxy) {
                BluetoothHeadset bluetoothHeadset = (BluetoothHeadset) proxy;
                Class btHeadsetCls = BluetoothHeadset.class;
                try {
                    Method connect = btHeadsetCls.getMethod("connect", BluetoothDevice.class);
                    connect.setAccessible(true);
                    Boolean connected = (Boolean) connect.invoke(bluetoothHeadset, device);
                    Toast.makeText(context, connected ? "发送信息成功，请查收" : "发送信息失败", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onServiceDisconnected(int profile) {
            }
        }, BluetoothProfile.HEADSET);
    }

    public static boolean isDeviceConnect(BluetoothAdapter blueToothClient, BluetoothDevice bondedDevice) {
        try {
            //获取连接状态
            Class<BluetoothAdapter> bluetoothAdapterClass = BluetoothAdapter.class;//得到BluetoothAdapter的Class对象
            Method method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);
            method.setAccessible(true);
            int state = (int) method.invoke(blueToothClient, (Object[]) null);
            if (state == BluetoothAdapter.STATE_CONNECTED) {
                System.out.println("isDeviceConnect========STATE_CONNECTED" + bondedDevice.getAddress());
            }
            //使用反射调用被隐藏的方法
            Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);
            isConnectedMethod.setAccessible(true);
            boolean isConnected = (boolean) isConnectedMethod.invoke(bondedDevice, (Object[]) null);
            if (isConnected) {
                System.out.println("isDeviceConnect========已经连接" + bondedDevice.getAddress());
            }
            return isConnected;
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return false;
    }
}
